﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.Data;
using System.Net.Mail;

namespace EuroAudit
{
    public partial class PassReset : System.Web.UI.Page
    {
        string UserName = "";
        GlobalF GFunc = new GlobalF();
        StringCollection PassChars = new StringCollection();

        protected void Page_Load(object sender, EventArgs e)
        {
            GFunc.InitO();

            for(int i = 0; i < 10 ; i++)
            {
                PassChars.Add(i.ToString());
            }
            for (int i = 65; i < 91; i++)
            {
                char PChar = (char)i;
                PassChars.Add(PChar.ToString());
            }
            for (int i = 97; i < 123; i++)
            {
                char PChar = (char)i;
                PassChars.Add(PChar.ToString());
            }
        }
        private string GeneratePass()
        {
            string NewPass = "";

            Random rndPass = new Random();
            int PassIdx;

            for (int i = 0; i < 6; i++)
            {
                PassIdx = rndPass.Next(0, 59);
                NewPass += PassChars[PassIdx];
            }

            return NewPass;
        }
        private void SavePass(string UserName, string Password)
        {
            byte[] EncPass;
            string SEncPass = "";
            string QString = "";
            SHA1 SHAProv = new SHA1CryptoServiceProvider();
            byte[] Pass2Byte = System.Text.Encoding.ASCII.GetBytes(Password);
            //Pass2Byte = txtPassword.Text.ToCharArray();
            EncPass = SHAProv.ComputeHash(Pass2Byte);
            SEncPass = BitConverter.ToString(EncPass).Replace("-", "").ToLower();
            if (UserName == string.Empty)
            {
                lblErr.Text = "Nav norādīts lietotāja vārds.";
                return;
            }
            QString = "UPDATE users SET Password='" + SEncPass + "' WHERE RecStatus=0 AND User='" + UserName + "'";
            GFunc.GetData(QString, "WebCNS", false);

        }

        private void SendPass(string EMail, string Password)
        {
            string MsgTo = "";

            if (string.IsNullOrEmpty(EMail))
            {
                lblErr.Text = "Nav norādīta e-pasta adrese.";
                return;
            }
            else
            {
                MsgTo = txtEmail.Text;
            }
            string SenderMail = "";
            DataSet dsOMailFrom = GFunc.GetData("SELECT OptValue FROM options WHERE OptType='GLOBAL' AND OptGroup='Mail' AND OptName='System e-mail'", "WebCNS", false);
            if (dsOMailFrom.Tables.Count > 0)
            {
                if (dsOMailFrom.Tables[0].Rows.Count > 0)
                {
                    SenderMail = dsOMailFrom.Tables[0].Rows[0]["OptValue"].ToString().Trim();
                }
            }
            if (SenderMail == string.Empty)
            {
                lblErr.Text = "Nevar atrast sūtītāja e-pasta adresi.";
                return;
            }

            MailMessage MMsg = new MailMessage();
            MailAddress FromAdr = new MailAddress(SenderMail);
            MMsg.From = FromAdr;
            string[] MsgRcp = MsgTo.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < MsgRcp.GetLength(0); i++)
            {
                MMsg.To.Add(MsgRcp[i]);
            }
            //aizpildam CC lauku, ja DB ir norādīti e-pasti
            /*string[] CCMail;
            string CCOption = "";
            dsOMailFrom = GFunc.GetData("SELECT OptValue FROM options WHERE OptType='GLOBAL' AND OptGroup='Mail' AND OptName='CC Users'", "WebCNS", false);
            if (dsOMailFrom.Tables.Count > 0)
            {
                if (dsOMailFrom.Tables[0].Rows.Count > 0)
                {
                    CCOption = dsOMailFrom.Tables[0].Rows[0]["OptValue"].ToString().Trim();
                }
            }
            if (CCOption.Length > 0)
            {
                CCMail = CCOption.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < CCMail.Length; i++)
                {
                    MailAddress CCAdr = new MailAddress(CCMail[i]);
                    MMsg.CC.Add(CCAdr);
                }
            }*/

            MMsg.Subject = "Paroles maiņa EuroAudit sistēmā";
            // HTML Body (remove HTML tags for plain text).
            string NewDocMsg = "EUROAUDIT sistēmā tika nomainīta parole lietotājam " + UserName + "";
            string MsgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" +
                    "<HTML>" +
                    "<HEAD>" +
                    "	<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=windows-1257\">" +
                    "</HEAD>" +
                    "<BODY LANG=\"lv-LV\" DIR=\"LTR\">" +
                    "<P><B>" + NewDocMsg + "</B></P>" +
                    "<P><BR>" +
                    "</P>" +
                    "<P>Jaunā parole: <B>" + Password + "</B></P>" +
                    "<P>Pēc ielogošanās nomainiet to uz jaunu.</B></P>" +
                    "</BODY>" +
                    "</HTML>";

            MMsg.Body = MsgBody;
            MMsg.IsBodyHtml = true;

            /*// ADD AN ATTACHMENT.
            String sFile = @"C:\temp\Hello.txt";
            MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64);

            oMsg.Attachments.Add(oAttch);
            */
            SmtpClient SMTPmail = new SmtpClient();
            SMTPmail.Host = GlobalF.AppOptions["SMTPServer"];
            SMTPmail.Send(MMsg);


            MMsg.Dispose();

            //oAttch = null;


        }
        protected void cmdSend_Click(object sender, EventArgs e)
        {
            try
            {
                lblErr.Text = string.Empty;
                if (txtEmail.Text == string.Empty)
                {
                    lblErr.Text = "Nav norādīta e-pasta adrese";
                    return;
                }
                DataSet dsUser = GFunc.GetData("SELECT User FROM users WHERE EMail='" + txtEmail.Text + "'", "WebCNS", false);
                if (dsUser.Tables.Count > 0)
                {
                    if (dsUser.Tables[0].Rows.Count > 0)
                    {
                        UserName = dsUser.Tables[0].Rows[0]["User"].ToString().Trim();
                    }
                }
                if (UserName == string.Empty)
                {
                    lblErr.Text = "Norādītais e-pasts nav reģistrēts.";
                    return;
                }

                string NewPassword = GeneratePass();
                SavePass(UserName, NewPassword);
                SendPass(txtEmail.Text, NewPassword);
                lblErr.Text = "Jaunā parole nosūtīta uz norādīto e-pastu.";
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }
        }
    }
}
